<template>
  <div>
    <div
      class="t-desc-text-content"
      v-html="content"
      @click="handleContentClick"
    />
    <el-image-viewer
      @close="closeImgViewer"
      :url-list="imageList"
      :initial-index="imgInitIndex"
      v-if="showImageViewer"
    />
  </div>
</template>

<script setup name="DescText">
import { computed, ref } from "vue";

const props = defineProps({
  content: {
    type: String,
    default: ""
  }
});
const imageList = computed(() => {
  const reg = /<img.*?src="(.*?)".*?>/g;
  const result = [];
  let temp;
  while ((temp = reg.exec(props.content))) {
    result.push(temp[1]);
  }
  return result;
});

const showImageViewer = ref(false);

const closeImgViewer = () => {
  showImageViewer.value = false;
};

const imgInitIndex = ref(0);

const handleContentClick = e => {
  if (e.target) {
    // 判断是不是点击的图片 是图片则获取图片地址
    if (e.target.tagName === "IMG") {
      const imgUrl = e.target.currentSrc;
      imgInitIndex.value = imageList.value.findIndex(item => item === imgUrl);
      showImageViewer.value = true;
    }
  }
  console.log(e);
};
</script>
<style lang="scss">
.t-desc-text-content {
  img {
    max-width: 100%;
    height: auto;
  }
}
</style>
